import time
import subprocess
from functools import partial

subprocess.Popen = partial(subprocess.Popen, encoding="utf-8")

from common import settings
import requests
import execjs


def js():
    with open('./tt.js', 'r', encoding='utf-8') as f:
        js_file = f.read()
    ctx = execjs.compile(js_file)
    return ctx.call('run')


def fetch(page: int):
    cookies = {
        'sessionid': '0ka417x2e52gjrjdfa0nvs57un7ow7xg',
    }

    headers = {
        'accept': 'application/json, text/javascript, */*; q=0.01',
        'accept-language': 'zh-CN,zh;q=0.9',
        'cache-control': 'no-cache',
        # 'cookie': 'Hm_lvt_c99546cf032aaa5a679230de9a95c7db=1714464818,1714638753,1714964192,1715582233; qpfccr=true; no-alert3=true; tk=-5773843510816912871; sessionid=0yprlq4t8ebsn0wer7bawyxw5u733fjv; Hm_lpvt_c99546cf032aaa5a679230de9a95c7db=1715584952',
        'pragma': 'no-cache',
        'priority': 'u=0, i',
        'referer': 'https://match.yuanrenxue.cn/match/16',
        'sec-ch-ua': '"Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
        'x-requested-with': 'XMLHttpRequest',
    }
    res = js()
    params = {
        'page': page,
        'm': res.get('m'),
        't': res.get('t')
        # 'm': 'bkERWwjdn73zB475038d86f9fce42fb3039c5849d928d1cPbAbSFPp3P',
        # 't': '1715673544000',
        # 'a': '1715673305331',
    }
    print('params', params)
    response = requests.get('https://match.yuanrenxue.cn/api/match/16'
                            , params=params, cookies=cookies, headers=headers
                            , proxies=settings.proxies,
                            )

    print(response.text)
    if response.status_code != 200:
        exit(500)
    else:
        pass
        # exit(200)
    return [x['value'] for x in response.json()['data']]


if __name__ == '__main__':
    values = []

    for page in range(1, 6):
        time.sleep(0.1)
        values.extend(fetch(page))
    print(sum(values))
